﻿using System;
using System.Collections.Generic;
using System.Text;
using CalibrationLibrary;

namespace CO2FixCalibration
{
    static class ManipCo2FixFile
    {
        private static string co2fixfilename;
        static  List<string> CO2FixFileContent;

        static public void Manipulate(int h, string label, Parameters parameters, string ManipCo2FileName, int simlength)
        {
            List<string> ManipCo2File = new List<string>(CO2FixFileContent);

            ManipCo2File = SetCAIRatios(ManipCo2File, parameters["CAIRatiosNonCommercial"].RunningValue, parameters["CAIRatiosCommercial"].RunningValue);

            ManipCo2File = SetMaxCohortBiomass(ManipCo2File, parameters);

            if (h == 0)
            {
                ClearHarvestFractions(ManipCo2File);
                System.IO.File.WriteAllLines(ManipCo2FileName, ManipCo2File.ToArray());
                return;
            }
            string ManagementType = label.Remove(label.Length - 1);
            if (parameters["HarvestIntensity" + ManagementType] != null && parameters["InitHarvestMort" + ManagementType] != null && parameters["HarvestMort_impyrs" + ManagementType] != null)
            {
                ManipCo2File = SetHarvestMort(ManipCo2File, parameters["HarvestIntensity" + ManagementType].RunningValue, parameters["InitHarvestMort" + ManagementType].RunningValue, parameters["HarvestMort_impyrs" + ManagementType].RunningValue);
            }

            if (parameters["HF_" + label] != null && parameters["HY_" + label] != null)
            {
                ManipCo2File = SetHarvestFractions(ManipCo2File, (int)Math.Round(parameters["HY_"+ label].RunningValue, 0), parameters["HF_" + label].RunningValue, simlength);
            }
            else
            {
                ManipCo2File = ClearHarvestFractions(ManipCo2File);
            }

           

            System.IO.File.WriteAllLines(ManipCo2FileName, ManipCo2File.ToArray());

        }

        private static List<string> SetCAIRatios(List<string> CO2FixFileContent, double CAIRatioNC, double CAIRatioComm)
        {
             
            foreach (string name in CohortNames.GetNames)
            {
                bool incohortdata = false;
                for (int r = 0; r < CO2FixFileContent.Count; r++)
                {
                    if (CO2FixFileContent[r].Contains(name) && CO2FixFileContent[r].Contains("cohort")) incohortdata = true;
                    if (incohortdata == true && CO2FixFileContent[r].Contains("# growth table"))
                    {
                        r += 3;
                        while (CO2FixFileContent[r].Contains("}") == false)
                        {
                            string[] terms = CO2FixFileContent[r].Trim().Split('\t');
                            double old_value = double.Parse(terms[terms.Length - 1]);

                            double new_value = new_value = Math.Round(old_value * CAIRatioNC, 2);
                            if (name.Contains("Commercial")) new_value = Math.Round(old_value * CAIRatioComm, 2);
                            terms[terms.Length - 1] = new_value.ToString();

                            string new_string = "\t\t\t\t\t";
                            foreach (string t in terms)
                            {
                                new_string += t + "\t";
                            }
                            new_string.TrimEnd();
                            CO2FixFileContent.RemoveAt(r);
                            CO2FixFileContent.Insert(r, new_string);
                            r++;
                        }
                       
                        incohortdata = false;
                    }


                }
            }
            return CO2FixFileContent;

             
        }
        private static List<string> ClearHarvestFractions(List<string> CO2FixFileContent)
        {
            foreach (string name in CohortNames.GetNames)
            {
                bool incohortdata = false;
                for (int r = 0; r < CO2FixFileContent.Count; r++)
                {
                    if (CO2FixFileContent[r].Contains(name) && CO2FixFileContent[r].Contains("cohort")) incohortdata = true;
                    if (incohortdata == true && CO2FixFileContent[r].Contains("# thinning and harvest table"))
                    {
                        r += 4;
                        while (CO2FixFileContent[r].Contains("}") == false)
                        {
                            CO2FixFileContent.RemoveAt(r);
                        }
                        incohortdata = false;
                    }
                }
            }



            return CO2FixFileContent;
        }
        private static List<string> SetHarvestFractions(List<string> CO2FixFileContent, int HarvestYear, double HarvestFractions, int simlength)
        {
            // SetHarvestFractions according to biomass in control plot
            foreach (string name in CohortNames.GetNames)
            {
                if (name.Contains("Commercial") == false) continue;

                bool incohortdata = false;
                for (int r = 0; r < CO2FixFileContent.Count; r++)
                {
                    if (CO2FixFileContent[r].Contains(name) && CO2FixFileContent[r].Contains("cohort")) incohortdata = true;
                    if (incohortdata == true && CO2FixFileContent[r].Contains("# thinning and harvest table"))
                    {
                        r += 4;
                        while (CO2FixFileContent[r].Contains("}") == false)
                        {
                            CO2FixFileContent.RemoveAt(r);
                        }
                        int hy = 0; // harvest year
                        int hc = 1; //harvest count 
                        if (HarvestYear>0) while (hy < simlength)
                        {
                            hy = hc * HarvestYear;
                            CO2FixFileContent.Insert(r, "\t\t\t\t\t" + hy + "\t" + Math.Round(HarvestFractions, 2) + "\t1	0	0	0	0.0	0.0	0	0");
                            hc++;
                            r++;
                        }
                        incohortdata = false;  
                    }
                     

                }
            }
            return CO2FixFileContent;
        }
        private static List<string> SetHarvestMort(List<string> CO2FixFileContent, double volume, double InitHarvestMort, double HarvestMort_impyrs)
        {
            // # management mortality
            for (int r = 0; r < CO2FixFileContent.Count; r++)
            {
                if (CO2FixFileContent[r].Contains("# management mortality") && CO2FixFileContent[r].Contains("# management mortality method")==false)  
                {
                    r += 3;
                    while (CO2FixFileContent[r].Contains("}") == false)
                    {
                        CO2FixFileContent.RemoveAt(r);
                    }

                    // 20	0.02	5
                    CO2FixFileContent.Insert(r, "\t\t\t\t\t" + Math.Round(volume,2) + "\t" + Math.Round(InitHarvestMort,2) + "\t" + Math.Round(HarvestMort_impyrs,2));
                     
                    r++;

                    //incohortdata = false;  
                }
            }
            return CO2FixFileContent;
        }
        /*
        private static List<string> SetMax_Biomass(List<string> CO2FixFileContent, Calibration.Parameters parameters)
        {
            // # max_biomass in the stand [Mg/ha]
            for (int r = 0; r < CO2FixFileContent.Count; r++)
            {
                if (CO2FixFileContent[r].Contains("# max_biomass in this cohort"))
                {
                   // double max_biom = double.Parse(CO2FixFileContent[r].Split(null as char[], StringSplitOptions.RemoveEmptyEntries)[0]);
                    CO2FixFileContent[r] = "\t\t\t\t" + parameters["max_biom"].RunningValue;
                }
            }
            return CO2FixFileContent;
        }
        */
        private static List<string> SetMaxCohortBiomass(List<string> CO2FixFileContent, Parameters parameters)
        {
            // Set Cohort-specific max biomass
            for (int r = 0; r < CO2FixFileContent.Count; r++)
            {
                string line = CO2FixFileContent[r];

                while (line.Contains("\""))line = line.Replace("\"", "");
              
                string[] terms = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
                
                if (terms.Length >0 && terms[0].Contains("cohort"))
                {
                    string par = "max_biom_" + terms[1];

                    if (parameters[par] != null)
                    {
                        r += 5; 
                    
                        CO2FixFileContent.RemoveAt(r);

                        CO2FixFileContent.Insert(r, parameters[par].RunningValue.ToString());
                    }

                   
                }
                
            }
            return CO2FixFileContent;
        }
         

        /*
        static public void Manipulate(string label, int[] HarvestYears, double HarvestFractions, double Volume, double InitHarvestMort, double HarvestMort_impyrs, double[] CAIRatios, string ManipCo2FileName)
        {
            double[] harvestfractions = new double[HarvestYears.Length];

            for (int yr = 0; yr < HarvestYears.Length; yr++)
            {
                harvestfractions[yr] = HarvestFractions;
            }
            Manipulate(label, HarvestYears, harvestfractions, Volume, InitHarvestMort, HarvestMort_impyrs, CAIRatios, ManipCo2FileName);
        }
         */
        //static public void Manipulate(string label, int[] HarvestYears, Calibration.Parameters parameters, string ManipCo2FileName)
       

         static public void Initialize(string CO2FixFileName)
         {
             co2fixfilename = CO2FixFileName;

             CO2FixFileContent = new List<string>(System.IO.File.ReadAllLines(CO2FixFileName));
         }


       
    }
}
